package bx.com.smartcashier.activity;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bx.com.smartcashier.R;
import bx.com.smartcashier.config.ServerUrl;
import bx.com.smartcashier.mode.SmartShopOrderDetail;
import bx.com.smartcashier.utils.JsonUtils;
import bx.com.smartcashier.view.CustomDatePicker;
import bx.com.smartcashier.view.DateFormatUtils;
import bx.com.smartcashier.view.TransactionFragment;


public class TransactionActivity extends AppCompatActivity implements View.OnClickListener,TransactionFragment.MyListener {

    private CustomDatePicker mDatePicker;
    private TextView tvDateStart,tvDateEnd,tvAllType;
    private ListView lvAll;
    private int whoSelect=1;//1开始时间   2结束时间
    private CustomDatePicker mTimerPicker;
    private int type=0;//0 全部  1 销售  2  退货
    private String token;
    private String shopId;
//    private List<SmartShopOrderDetailVO> returnDetails=new ArrayList<>();//退货
//    private List<SmartShopOrderDetailVO> saleDetails=new ArrayList<>();//销售

    private List<SmartShopOrderDetail> shows=new ArrayList<>();
    private BaseAdapter adapter;
    private BigDecimal totalPrice=new BigDecimal("0.00");
    private TextView tvTotalPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        initDatePicker();
        initTimerPicker();
        setListeners();
        SharedPreferences sharedPreferences = getSharedPreferences("User",0);
        token = sharedPreferences.getString("token","null");
        shopId = sharedPreferences.getString("shopId","null");
        getData();
        showData();
        addToolbar();
    }

    private void addToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
//        //设置是否有返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    }
    private void showData() {

        adapter=new BaseAdapter(){

            @Override
            public int getCount() {
                return shows.size();
            }

            @Override
            public SmartShopOrderDetail getItem(int position) {
                return shows.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                final SmartShopOrderDetail one = getItem(position);
                View view;
                ViewHolder viewHolder;

                if (convertView == null){
                    // inflate出子项布局，实例化其中的图片控件和文本控件
                    view = LayoutInflater.from(TransactionActivity.this).inflate(R.layout.goods_detail_item, null);

                    viewHolder = new ViewHolder();
                    // 通过id得到图片控件实例
                    viewHolder.goodsDetail = (TextView) view.findViewById(R.id.tv_goods_detail);
                    // 通过id得到文本空间实例
                    viewHolder.date = (TextView) view.findViewById(R.id.tv_goods_date);
                    viewHolder.price= (TextView)view.findViewById(R.id.tv_price);
                    // 缓存图片控件和文本控件的实例
                    view.setTag(viewHolder);
                }else{
                    view = convertView;
                    // 取出缓存
                    viewHolder = (ViewHolder) view.getTag();
                }

                viewHolder.goodsDetail.setText(one.getGoodsName());
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
                viewHolder.date.setText(simpleDateFormat.format(one.getGmtCreate()));
                // 文本控件设置文本内容
                if(one.getIsSale()){
                    viewHolder.date.setTextColor(Color.rgb(0, 0, 255));

                    viewHolder.price.setTextColor(Color.rgb(0, 0, 255));
                    viewHolder.price.setText("+  ￥"+one.getRetailPrice());
                }else{
                    viewHolder.date.setTextColor(Color.rgb(255, 0, 0));
                    viewHolder.price.setTextColor(Color.rgb(255, 0, 0));
                    viewHolder.price.setText("-  ￥"+(one.getRetailPrice().multiply(new BigDecimal(one.getReturnCount())).multiply(new BigDecimal(one.getDiscountRate())).divide(new BigDecimal("10"))));
                }

                return view;
            }
            // 内部类
            class ViewHolder{
                TextView goodsDetail;
                TextView date;
                TextView price;
            }

        };
        lvAll.setAdapter(adapter);

    }

    /**
     * 网络获取数据
     */
    private void getData() {
        String url="/SmartShopOrder/selectSellGoodsList.json";
//        String url="/SmartShopOrder/selectSellHistoryList.json";

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                ServerUrl.url + url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        s = s.replace(" ","");
                        Map<String,Object> map = JsonUtils.getMap(s);
                        if(String.valueOf(map.get("code")).equals("000000"))
                        {
                            List<SmartShopOrderDetail> vo = null;
                            try {
                                Map<String,Object> data =JsonUtils.getMap(String.valueOf(map.get("data")));
                                if(!"0".equals(String.valueOf(data.get("total")))){
                                    ObjectMapper mapper = new ObjectMapper();
                                    JavaType collectionType = getCollectionType(mapper, List.class, SmartShopOrderDetail.class);
                                     vo =  (List<SmartShopOrderDetail>)mapper.readValue(String.valueOf( data.get("result")), collectionType);

                                    if(vo==null||vo.size()<=0){
                                        shows.clear();
                                        Toast.makeText(TransactionActivity.this,"数据为空",Toast.LENGTH_LONG).show();
                                    }else {

                                        List<SmartShopOrderDetail> returnDetails=new ArrayList<>();
                                        List<SmartShopOrderDetail> saleDetails=new ArrayList<>();

                                        for (int i = 0; i <vo.size() ; i++) {
                                            if(vo.get(i).getStatus()==1){
                                                saleDetails.add(vo.get(i));
                                            }else if(vo.get(i).getStatus()==2){
                                                returnDetails.add(vo.get(i));
                                            }
                                        }
//                                        returnDetails = vo.getReturnSmartShopOrderDetailVOS();
//                                        saleDetails = vo.getSmartShopOrderDetailVOS();

                                        if (type == 0) {
                                            shows.clear();
                                            for (int i = 0; i < returnDetails.size(); i++) {
                                                returnDetails.get(i).setIsSale(false);
                                            }
                                            shows.addAll(returnDetails);
                                            shows.addAll(saleDetails);
                                        } else if (type == 1) {
                                            shows.clear();
                                            shows.addAll(saleDetails);
                                        } else if (type == 2) {
                                            shows.clear();
                                            for (int i = 0; i < returnDetails.size(); i++) {
                                                returnDetails.get(i).setIsSale(false);
                                            }
                                            shows.addAll(returnDetails);
                                        }
                                    }



                                }else{
                                    shows.clear();
                                    Toast.makeText(TransactionActivity.this,"数据为空",Toast.LENGTH_LONG).show();
                                }
                                adapter.notifyDataSetChanged();
                                jsJg();


                            } catch (Exception e) {
                                Toast.makeText(TransactionActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                                e.printStackTrace();
                            }

                        }
                        else
                        {
                            Toast.makeText(TransactionActivity.this, JsonUtils.getMap(s).get("msg").toString(), Toast.LENGTH_SHORT).show();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(TransactionActivity.this, "获取信息异常!", Toast.LENGTH_SHORT).show();

            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("shopId",shopId);
                map.put("token",token);
                map.put("startTime",tvDateStart.getText().toString()+" 00:00:00");
                map.put("endTime",tvDateEnd.getText().toString()+" 23:59:59");
                map.put("pageNum","1");
                map.put("pageSize","10000");
                if (type == 0) {

                } else if (type == 1) {
                    map.put("status","1");
                } else if (type == 2) {
                    map.put("status","2");
                }
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(60*1000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }


    /**
     * 获取泛型的Collection Type
     * @param collectionClass 泛型的Collection
     * @param elementClasses 实体bean
     * @return JavaType Java类型
     */
    public static JavaType getCollectionType(ObjectMapper mapper, Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    /**
     * 计算价格
     */
    private void jsJg() {
        totalPrice=new BigDecimal("0.00");
        for (int i = 0; i < shows.size(); i++) {
            SmartShopOrderDetail one = shows.get(i);
            if(shows.get(i).getIsSale()){
                totalPrice=totalPrice.add(shows.get(i).getRetailPrice()==null?new BigDecimal("0.00"):shows.get(i).getRetailPrice());
            }else{
                totalPrice=totalPrice.subtract((one.getRetailPrice().multiply(new BigDecimal(one.getReturnCount())).multiply(new BigDecimal(one.getDiscountRate())).divide(new BigDecimal("10"))));
            }
        }
        if(totalPrice.compareTo(new BigDecimal("0.00"))==-1){
            tvTotalPrice.setTextColor(Color.rgb(255, 0, 0));
        }else{
            tvTotalPrice.setTextColor(Color.rgb(0, 0, 255));

        }
        tvTotalPrice.setText("￥"+totalPrice+"");
    }

    private void setListeners() {
        tvDateStart.setOnClickListener(this);
        tvDateEnd.setOnClickListener(this);
        tvAllType.setOnClickListener(this);
    }

    private void initViews() {
        setContentView(R.layout.activity_transaction);
        tvDateStart = findViewById(R.id.tv_date_start);
        tvDateEnd= findViewById(R.id.tv_date_end);
        tvAllType=findViewById(R.id.tv_all_type);
        lvAll=findViewById(R.id.lv_all);
        tvTotalPrice=findViewById(R.id.tv_total_price);
    }


    private void initDatePicker() {
        long beginTimestamp = DateFormatUtils.str2Long("2009-05-01", false);
        long nowtime = System.currentTimeMillis();
        Calendar calender = Calendar.getInstance();
        calender.add(Calendar.YEAR,10);
        long endTimestamp = calender.getTime().getTime();
        tvDateStart.setText(DateFormatUtils.long2Str(nowtime, false));

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                if(whoSelect==1){
                    tvDateStart.setText(DateFormatUtils.long2Str(timestamp, false));
                }else if(whoSelect==2){
                    tvDateEnd.setText(DateFormatUtils.long2Str(timestamp, false));
                }
                getData();
            }
        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(false);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_date_start:
                // 日期格式为yyyy-MM-dd
                mDatePicker.show(tvDateStart.getText().toString());
                whoSelect=1;
                break;

            case R.id.tv_date_end:
                // 日期格式为yyyy-MM-dd HH:mm
                mDatePicker.show(tvDateEnd.getText().toString());
                whoSelect=2;
                break;
            case R.id.tv_all_type:

                TransactionFragment TransactionFragment=new TransactionFragment();
                Bundle bundle=new Bundle();
                TransactionFragment.setArguments(bundle);
                TransactionFragment.show(getSupportFragmentManager(),"transactionFragment");

                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDatePicker.onDestroy();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            finish();
        }
        return super.onOptionsItemSelected(item);
    }


    private void initTimerPicker() {
        Date  now=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String beginTime =simpleDateFormat.format(now);
        Calendar calender = Calendar.getInstance();
        calender.add(Calendar.DATE,1);
        long endTimestamp = calender.getTime().getTime();
        String endTime = DateFormatUtils.long2Str(endTimestamp, true);

        tvDateEnd.setText(sdf.format(now));

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mTimerPicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                tvDateEnd.setText(DateFormatUtils.long2Str(timestamp, true));
            }
        }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker.setCancelable(true);
        // 显示时和分
        mTimerPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker.setCanShowAnim(true);
    }


    @Override
    public int sendValue(int value) {
        type=value;
        getData();
        if(value==0){
            tvAllType.setText("全部交易类型");
        }else if(value==1){
            tvAllType.setText("销售详情");
        }else if(value==2){
            tvAllType.setText("退货详情");
        }

        return 1;
    }
}
